﻿using Avalonia;
using System;
using System.IO;
using System.Reflection;
using Xilium.CefGlue;

namespace CefGlue.Avalonia
{
    public static class CefGlueApplicationExtensions
    {
        public static AppBuilder ConfigureCefGlue(this AppBuilder builder, string[] args)
        {
            return builder.AfterSetup((b) =>
            {
                try
                {
                    //CefRuntimeExtension.SetDllImportResolver();
                    CefRuntime.Load();
                }

                catch (Exception ex)
                {
                    LogHelper.Error(ex, "CefRuntime.Load");
                }

                var mainArgs = new CefMainArgs(args);
                var cefApp = new SampleCefApp();
                cefApp.RegisterCustomSchemes += CefApp_RegisterCustomSchemes;
                cefApp.WebKitInitialized += CefApp_WebKitInitialized;

                //var exitCode = CefRuntime.ExecuteProcess(mainArgs, cefApp, IntPtr.Zero);
                //if (exitCode != -1) { return; }
                String subBrowserPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Assembly.GetEntryAssembly().FullName.Split(',')[0].Trim());
                var location = System.Reflection.Assembly.GetEntryAssembly().Location;
                var directory = System.IO.Path.GetDirectoryName(location);

                var cefSettings = new CefSettings
                {
                    MultiThreadedMessageLoop = false,// CefRuntime.Platform == CefRuntimePlatform.Windows,//这个设为false时，cef不会执行任何消息事件，也不会加载页面，需要手动执行消息循环
                    LogSeverity = CefLogSeverity.Error,
                    LogFile = Path.Combine(directory, "log", $"ceflogs-{DateTime.Now:yyyy-MM-dd}.log"),
                    RemoteDebuggingPort = CommonConst.CefDebugPort,
                    LocalesDirPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "locales"),
                    //BrowserSubprocessPath = Path.Combine(BasePath, "cefclient.exe"),
                    ResourcesDirPath = AppDomain.CurrentDomain.BaseDirectory,
                    NoSandbox = true,
                    BackgroundColor = new CefColor((byte)0, (byte)0, (byte)0, (byte)0),
                    WindowlessRenderingEnabled = true,
                    ExternalMessagePump = true,
                    CommandLineArgsDisabled = false,
                    Locale = "zh-CN"
                };
                if (OperatingSystem.IsMacOS())
                {
                    String helperpath = "Contents/Frameworks/&lt;app&gt; Helper.app/Contents/MacOS/&lt;app&gt; Helper".Replace("&lt;app&gt;", "cefclient");
                    String macosSubProcessPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, helperpath);
                    //cefSettings.BrowserSubprocessPath = subBrowserPath;
                    cefSettings.FrameworkDirPath = AppDomain.CurrentDomain.BaseDirectory;
                }
                try
                {
                    CefRuntime.EnableHighDpiSupport();
                    CefRuntime.Initialize(mainArgs, cefSettings, cefApp, IntPtr.Zero);
                }
                catch (CefRuntimeException ex)
                {
                    LogHelper.Error(ex, "CefRuntime.Initialize Error");
                }
            });
        }

        private static void CefApp_WebKitInitialized(object sender, EventArgs e)
        {
            AvaloniaCefBrowser.OnWebKitInitialized(sender, e);
        }

        private static void CefApp_RegisterCustomSchemes(object sender, RegisterCustomSchemesEventArgs e)
        {
            AvaloniaCefBrowser.OnRegisterCustomSchemes(sender, e);
        }
    }
}
